﻿using IRepository;
using IService.Blog;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Blog
{
    public class MenusService: IMenusService
    {
        readonly ILogger<MenusService> logger;
        readonly IBaseRepository baseRepository;
        public MenusService(ILogger<MenusService> _logger, IBaseRepository _baseRepository)
        {
            logger = _logger;
            baseRepository = _baseRepository;
        }

        #region Get

        /// <summary>
        /// 查询所有菜单（分页）
        /// </summary>
        /// <param name="offset">页数</param>
        /// <param name="limit">每页数</param>
        /// <returns></returns>
        public async Task<MessageModel<PageInfoModel<BMenu>>> GetAllToPage(int offset = 1, int limit = 15)
        {
            try
            {
                PageInfoModel<BMenu> result = await baseRepository.QueryPage<BMenu>(offset, limit, "ID");

                return new MessageModel<PageInfoModel<BMenu>>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<PageInfoModel<BMenu>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 按角色ID查询所有菜单（分页）
        /// </summary>
        /// <param name="roleID">角色ID</param>
        /// <returns></returns>
        public async Task<MessageModel<List<BMenu>>> GetAllToPageByRoleID(int roleID = 1)
        {
            try
            {
                List<BMenu> menus= await baseRepository.Query<BMenu>();
                List<BRoleMenu> roleMenus = await baseRepository.Query<BRoleMenu>(n => n.RoleID == roleID);
                //List<object> list = await baseRepository.QueryBySql($"select m.* from BMenu m,BRoleMenu r where m.ID=r.MenuID and r.RoleID={roleID}");
                List<BMenu> list = new List<BMenu>();
                foreach (var item in roleMenus)
                {
                    BMenu menu = baseRepository.Query<BMenu>(n => n.ID == item.MenuID).Result.FirstOrDefault();
                    list.Add(menu);
                };

                return new MessageModel<List<BMenu>>()
                {
                    Code = 20000,
                    Data = list,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BMenu>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询所有菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BMenu>>> GetAll()
        {
            try
            {
                List<BMenu> result = await baseRepository.Query<BMenu>();
                //string FunName = MethodBase.GetCurrentMethod().DeclaringType.Name;//获取当前方法名
                //FunName = FunName.Substring(FunName.IndexOf('<')+1,FunName.LastIndexOf('>')-1);
                //LogLock.OutLogFile("UserService_GetAll", "", JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BMenu>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BMenu>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 根据条件表达式查询数据列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>数据列表</returns>
        public async Task<MessageModel<List<BMenus>>> GetByExpression<BMenus>(Expression<Func<BMenus, bool>> whereExpression)
        {
            try
            {
                List<BMenus> result = await baseRepository.Query(whereExpression);
                //LogLock.OutLogFile("GetByExpression", JsonConvert.SerializeObject(whereExpression), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BMenus>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BMenus>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询菜单按ID
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<BMenu>> GetById(int id)
        {
            try
            {
                BMenu result = await baseRepository.Query<BMenu>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<BMenu>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BMenu>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Post(BMenu parameter)
        {
            try
            {
                parameter.CreatedAt = DateTime.Now;
                //获取菜单ID
                parameter.ID = await baseRepository.Add(parameter);
                //LogLock.OutLogFile("Post", JsonConvert.SerializeObject(parameter), JsonConvert.SerializeObject(parameter), true);//存入日志
                return new MessageModel<string>()
                {
                    Code = 200,
                    Data = parameter.ID.ObjToString(),
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Put
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Put(BMenu parameter)
        {
            try
            {
                parameter.UpdatedAt = DateTime.Now;
                bool flag = await baseRepository.Update(parameter);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = parameter.ID.ObjToString(),
                        Message = "修改成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "修改失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Delete
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DelById(int id)
        {
            try
            {
                bool flag = await baseRepository.DeleteById<BMenu>(id);
                //LogLock.OutLogFile("DelById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(flag), true);//存入日志
                return new MessageModel<bool>()
                {
                    Code = 200,
                    Data = flag,
                    Message = "删除成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

    }
}
